<template>
    <div class="codeEdit">
        <textarea ref="codeContainer" v-model="code"></textarea>
    </div>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/lib/codemirror.css'

import 'codemirror/theme/base16-light.css'
import 'codemirror/theme/base16-dark.css'

import 'codemirror/mode/vue/vue'

import 'codemirror/addon/edit/matchbrackets'
import 'codemirror/addon/edit/matchtags'

import 'codemirror/addon/edit/closebrackets'
import 'codemirror/addon/edit/closetag'

import 'codemirror/addon/fold/foldgutter.css'
import 'codemirror/addon/fold/brace-fold'
import 'codemirror/addon/fold/foldcode'
import 'codemirror/addon/fold/foldgutter'
import 'codemirror/addon/fold/comment-fold'

import 'codemirror/addon/fold/indent-fold'

import 'codemirror/addon/selection/active-line'

export default {
    name: 'codeEdit',
    props: {
        value: {
            type: String
        },
        codeHandler: {
            type: Function
        }
    },
    data() {
        return {
            codeEditor: null,
            code: '',
            defaultOptions: {
                mode: 'text/x-vue',
                gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
                lineNumbers: true,
                theme: 'base16-dark'
            }
        }
    },
    watch: {
        value(val) {
            const editorVal = this.codeEditor.getValue()
            if(val!=editorVal) {
                this.codeEditor.setValue(this.value)
            }
        },
        immediate: true,
        deep: true,
    },
    mounted() {
        this._initEdit()
    },
    methods: {
        _initEdit() {
            this.codeEditor = CodeMirror.fromTextArea(
                this.$refs.codeContainer,
                this.defaultOptions
            )
            this.codeEditor.setValue(this.value)
            this.codeEditor.on("change",(item) => {
                this.codeHandler(item.getValue())
            })
        }
    }

}
</script>

<style lang="less">
/deep/ .CodeMirror {
    height: 500px!important;
}
</style>